# gozerlib/plugs/fleet.py
#
#

""" the fleet makes it possible to run multiple bots. """

## gozerlib  imports
from gozerlib.fleet import fleet, FleetBotAlreadyExists
from gozerlib.commands import cmnds
from gozerlib.examples import examples
from gozerlib.aliases import aliasset
from gozerlib.config import cfg, Config
from gozerlib.tests import tests

## basic imports

import os
import logging

def handle_fleetavail(bot, ievent):

    """ show available fleet bots. """

    ievent.reply('available bots: ', fleet.avail()) 

cmnds.add('fleet-avail', handle_fleetavail, 'OPER')
examples.add('fleet-avail', 'show available fleet bots', 'fleet-avail')

def handle_fleetlist(bot, ievent):

    """ fleet-list .. list bot names in fleet. """

    ievent.reply("fleet: ", fleet.list(), dot=True)

cmnds.add('fleet-list', handle_fleetlist, ['USER', 'WEB'])
examples.add('fleet-list', 'show current fleet list', 'fleet-list')
tests.add('fleet-add local test localhost').add('fleet-list local').add('fleet-del local')

def handle_fleetadd(bot, ievent):

    """ fleed-addjabber <name> <host> <user> <password> [port] .. add jabber 
        bot to fleet.
    """

    length  = len(ievent.args)

    if length == 2:
        (name, type) = ievent.args
    else:
        ievent.missing('<name> <type>')
        return

    if fleet.byname(name):
        ievent.reply('we already have a bot with %s name in fleet' % \
name)
        return

    if '--owner' in ievent.optionset:
        owner = ievent.options['--owner']
    else:
        owner = cfg['owner']

    cfg = Config('fleet/' + name, '/config')
    cfg['enable'] = 1
    cfg['owner'] = owner
    cfg['name'] = name
    cfg['type'] = type
    cfg.save()
    b = fleet.makebot(name, type, cfg)
    ievent.reply('adding %s bot' % name)
    fleet.addbot(b)
    ievent.reply('%s started' % name)

cmnds.add('fleet-add', handle_fleetadd, 'OPER')
examples.add('fleet-add', 'fleet-add <name> <type> .. add new server to fleet', 'fleet-add test2 xmpp')

def handle_fleetdel(bot, ievent):

    """ fleet-del <botname> .. delete bot from fleet. """

    try:
        name = ievent.args[0]
    except IndexError:
        ievent.missing('<name>')
        return

    try:
        if fleet.delete(name):
            ievent.reply('%s deleted' % name)
        else:
            ievent.reply('%s delete failed' % name)
    except Exception, ex:
        ievent.reply(str(ex))

cmnds.add('fleet-del', handle_fleetdel, 'OPER', threaded=True)
examples.add('fleet-del', 'fleet-del <botname> .. delete bot from fleet list', 'fleet-del test')
tests.add('fleet-add local test localhost').add('fleet-del local', 'deleted')

def docmnd(bot, ievent):

    """ do command on bot/all bots. """

    try:
        name = ievent.args[0]
        cmnd = ' '.join(ievent.args[1:])
    except IndexError:
        ievent.missing('<name> <cmnd>')
        return

    if not cmnd:
        ievent.missing('<name> <cmnd>')
        return

    if cmnd.find('cmnd') != -1:
        ievent.reply("no looping please ;]")
        return

    try:
        if name == 'all':
            fleet.cmndall(ievent, cmnd)
        else:
            fleet.cmnd(ievent, name, cmnd)
    except Exception, ex:
        ievent.reply(str(ex))

cmnds.add('cmnd', docmnd, ['USER', 'WEB'], threaded=True)
examples.add('cmnd', "cmnd all|<botname> <cmnd> .. excecute command on bot with <name> or on all fleet bots", '1) cmnd main st 2) cmnd all st')
tests.add('fleet-add local test localhost').add('cmnd --chan #dunkbots local nicks')

def fleet_disable(bot, ievent):

    """ disable a fleet bot. """

    if not ievent.rest:
        ievent.missing("list of fleet bots")
        return

    bots = ievent.rest.split()

    for name in bots:
        bot = fleet.byname(name)
        if bot:
            bot.cfg['enable'] = 0
            bot.cfg.save()
            ievent.reply('disabled %s' % name)
            fleet.exit(name)
        else:
            ievent.reply("can't find %s bot in fleet" % name)

cmnds.add('fleet-disable', fleet_disable, 'OPER')
examples.add('fleet-disable', 'disable a fleet bot', 'fleet-disable local')
tests.add('fleet-add local test localhost').add('fleet-disable local', 'disabled')

def fleet_enable(bot, ievent):

    """ enable a fleet bot. """

    if not ievent.rest:
        ievent.missing("list of fleet bots")
        return

    bots = ievent.rest.split()

    for name in bots:
        bot = fleet.byname(name)

        if bot:
            bot.cfg.load()
            bot.cfg['enable'] = 1
            bot.cfg.save()
            ievent.reply('enabled %s' % name)
            start_new_thread(fleet.connect, (name, ))
        elif name in fleet.avail():
            bots = fleet.start([name, ], enable=True)
            for bot in bots:
                bot.cfg.load()
                bot.cfg['enable'] = 1
                bot.cfg.save()
                ievent.reply('enabled and started %s bot' % name)
        else:
            ievent.reply('no %s bot in fleet' % name)

cmnds.add('fleet-enable', fleet_enable, 'OPER', threaded=True)
examples.add('fleet-enable', 'enable a fleet bot', 'fleet-enable local')
tests.add('fleet-add local test localhost').add('fleet-disable local').add('fleet-enable local')
